package com.spring.demo.springdemo.config;

import com.spring.demo.springdemo.annotation.MyMapperScan;
import com.spring.demo.springdemo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author RenPu
 * @Date 2024/2/18 15:11
 * @Version 1.0
 * @Description: 根据代理对象生成BeanDefinition对象，并且注册到BeanDefinitionRegistry中供spring使用
 *
 *                1：解析注解中对应的路径值
 *                2：
 *                核心执行链路：MybatisImportRegisterBeanDefinitio（解析mapperScan注解配置的路径） ==》
 *                MybatisBeanDefinitionScanner（重写spring的Bean） ==》MybatisFactoryBeanConf
 *
 **/

@Slf4j
public class MybatisImportRegisterBeanDefinitio implements ImportBeanDefinitionRegistrar {


    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
        //扫描指定的包路径，实现根据接口类型灵活生成BeanDefinition对象
        String path = (String)annotationMetadata.getAnnotationAttributes(MyMapperScan.class.getName()).get("basePackage");
        log.info("获取 MyMapperScan 注解的包路径值为：：：："+path);

        MybatisBeanDefinitionScanner definitionScanner = new MybatisBeanDefinitionScanner(registry);

        //设置新设定的扫描规则
        definitionScanner.addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                return true;
            }
        });

        definitionScanner.doScan(path);


//        AbstractBeanDefinition userBeanDefinition =   BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//        userBeanDefinition.setBeanClass(MybatisFactoryBeanConf.class);
//        //此处为MybatisFactoryBeanConf中的mapperInterface赋值，利用指定构造方法的形式生成对应的代理对象
//        userBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);
//        registry.registerBeanDefinition("userMapper",userBeanDefinition);
    }
}
